
declare interface EventHandler {
    thisTarget: any;
    handler: (...any: any[]) => void;
}

/**
 *自身带有事件处理功能的类
 *
 * @export
 * @class EventHandlerTarget
 */
export class EventHandlerTarget {

    private eventHandlers: Map<string, Set<EventHandler>> = new Map<string, Set<EventHandler>>();

    /**
     *注册事件
     *
     * @param {string} eventName 事件名
     * @param {Function} callback 回调
     * @param {object} target 回调执行指向对象
     * @memberof Client
     */
    public on(eventName: string, callback: (...any: any[]) => void, target: object) {
        var fns = this.eventHandlers.get(eventName);
        if (!fns) fns = new Set<EventHandler>();
        fns.add({
            thisTarget: target,
            handler: callback
        });
        this.eventHandlers.set(eventName, fns);
    }

    /**
     * 注销事件
     *
     * @param {string} eventName 事件名
     * @param {Function} callback 回调
     * @param {object} target 回调执行指向对象
     * @memberof Client
     */
    public off(eventName: string, callback: (...any: any[]) => void, target: object) {
        var fns = this.eventHandlers.get(eventName);
        if (fns) {
            fns.forEach((item) => {
                if (item.handler === callback && item.thisTarget === target) {
                    fns!.delete(item);
                }
            });
        }
    }
    /**
     * 触发事件
     *
     * @param {string} eventName 事件名
     * @param {any[]} eventParams 传给回调的参数
     * @memberof Client
     */
    public emit(eventName: string, ...eventParams: any[]) {
        var fns = this.eventHandlers.get(eventName);
        if (fns) {
            fns.forEach((item) => {
                item.handler.apply(item.thisTarget, eventParams);
            });
        }
    }
}